package com.lottery.job.utils;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;

import com.lottery.job.cqssc.CqsscScheduledJob;

/**
 * 
 * @描述: 彩票结果工具类
 *
 * @author LiBing
 * @date 2016年10月21日 下午4:52:11
 *
 */
public class JobHttpClient {
	
	private static Logger logger = Logger.getLogger(CqsscScheduledJob.class);
	
	/**
	 * 
	 * @描述: 通过GET方式发起http请求
	 * 
	 * @param url 彩票结果查询的URL
	 * @param times 查询成功前的查询次数
	 * @param invoker 方法调用者
	 * @return
	 */
	public static String sendGetRequest(String url,int times, String invoker) {
		logger.info(invoker+" begin to send get http request."+" url:"+url+" sender:"+invoker);
		GetMethod get = new GetMethod(url);

		HttpClient httpClient = new HttpClient();
		int statusCode = 500;
		int ts = 0;
		String result = null;
		while(statusCode!=HttpStatus.SC_OK && ts<times){
			try {
				if(ts==0){
					statusCode = httpClient.executeMethod(get);
				}else{
					Thread.sleep(1000 * 3);				
					statusCode = httpClient.executeMethod(get);
				}
				result = get.getResponseBodyAsString();
				ts++;
				continue;
			} catch (Exception e) {
				logger.error("encounter exception when sending get http request", e);
			}
		}
		return result;
	}

}
